<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="修改默认供应商"
    width="1200"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <div class="mb-4 updateSupplier">
      <vxe-table
        show-overflow
        :data="tableData"
        :column-config="{ resizable: true }"
        :edit-config="{ trigger: 'click', mode: 'cell' }"
        height="600"
      >
        <vxe-column field="sku" title="SKU" width="90">
          <template #default="{ row }">
            <div>{{ row?.goods_sku?.sku || "-" }}</div>
          </template>
        </vxe-column>
        <vxe-column field="sku" title="产品中文名" width="200">
          <template #default="{ row }">
            <vText :value="row?.goods_sku?.sku_cn_title"></vText>
          </template>
        </vxe-column>
        <vxe-column field="" title="默认供应商" width="200">
          <template #header>
            <div>默认供应商</div>
            <div>
              <el-button type="primary" link @click="handleSelectSupplier('batch')"
                >批量</el-button
              >
            </div>
          </template>
          <template #default="{ row, rowIndex }">
            <template v-if="row.is_wait_change_order">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="row.tooltip"
                placement="top-start"
              >
                <span class="text-[#999]">{{ row.supplier_name }}</span>
              </el-tooltip>
            </template>
            <div class="flex justify-between items-center" v-else>
              <div class="w-[140px]">
                <VText :value="row.supplier_name"></VText>
              </div>
              <el-button
                type="primary"
                link
                @click="handleSelectSupplier('row', rowIndex)"
                >选择</el-button
              >
            </div>
          </template>
        </vxe-column>
        <vxe-column field="is_refund_tax" title="是否退税" width="120">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.tooltip"
              placement="top-start"
              :disabled="!row.is_wait_change_order"
            >
              <el-select
                class="w-full"
                v-model="row.is_refund_tax"
                placeholder="请选择"
                @change="changeRefundTax(row)"
                :disabled="row.is_wait_change_order"
              >
                <el-option
                  v-for="item in refundTaxOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="unit_price" title="采购未税报价" width="110">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.tooltip"
              placement="top-start"
              :disabled="!row.is_wait_change_order"
            >
              <el-input
                v-model="row.unit_price"
                placeholder="请输入"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{3})\d+/, '$1')"
                @blur="blurcalculate(row, 'unit_price')"
                :disabled="row.is_wait_change_order"
              ></el-input>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="unit_price_tax" title="采购含税价" width="110">
          <template #default="{ row }">
            {{ row.unit_price_tax }}
          </template>
        </vxe-column>
        <vxe-column field="purchase_untaxed_price" title="采购未税价" width="110">
          <template #default="{ row }">
            {{ row.purchase_untaxed_price }} {{ row.currency }}
          </template>
        </vxe-column>
        <vxe-column field="tax_rate" title="供应商税点" width="100">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.tooltip"
              placement="top-start"
              :disabled="!row.is_wait_change_order"
            >
              <el-input
                v-model="row.tax_rate"
                placeholder="请输入"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                @blur="blurcalculate(row, 'tax_rate')"
                :disabled="row.is_refund_tax == 3 || row.is_wait_change_order"
              ></el-input>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="invoice_tax_rate" title="发票税点" width="120">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.tooltip"
              placement="top-start"
              :disabled="!row.is_wait_change_order"
            >
              <el-input
                v-model="row.invoice_tax_rate"
                placeholder="请输入"
                oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
                @blur="blurcalculate(row, 'finance_tax')"
                :disabled="row.is_refund_tax == 3 || row.is_wait_change_order"
              ></el-input>
            </el-tooltip>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="text-[#999]">
      <p>注：</p>
      <p>
        1、更换供应商，系统自动生成变更单，审核通过后执行修改系统会自动新增一条数据；并自动调整为默认供应商；
      </p>
      <p>
        2、更换供应商后，系统会自动获取采购-供应商管理中维护的供应商税点、发票税点重新计算采购价格；
      </p>
    </div>
    <template #footer>
      <div class="footer-btn">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="visibleSupplier"
    v-if="load"
    title="选择供应商"
    width="300"
    draggable
    @close="closeSupplier"
    :z-index="2000"
  >
    <el-select-v2
      v-model="formValues.supplier_id"
      style="width: 240px"
      filterable
      remote
      :remote-method="supplierMethod"
      clearable
      :options="supplierOption"
      :loading="optionLoading"
      placeholder="搜索供应商"
      @change="BatchSupplierChange"
    />
    <template #footer>
      <div class="footer-btn">
        <el-button @click="closeSupplier">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="saveSupplier"
          >保 存</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplier, batchUpdateSupplier, getSKUSupplierList } from "../api.js";
import { reactive } from "vue";
import { refundTaxOptions } from "../data.js";
import { getSupplierList, getSKUSupplier } from "@/api/index.js";
import { change_order_category, oversea_location_category } from "@/utils/data.js";

const visible = ref(false);
const loading = ref(false);
const tableData = ref([]);
const ids = ref({});
const supplierList = ref([]);
const supplierOption = ref([]);
const load = ref(false);
const rowIndex = ref(null);

const supplierMethod = async (query) => {
  // debounce(querySupplier(query), 300);
  if (query) {
    optionLoading.value = true;
    try {
      const { data } = await getSupplierList({
        page: 1,
        page_size: 1000,
        supplier_name: query,
      });
      supplierOption.value =
        data.map((i) => {
          i.value = i.s_id;
          i.label = i.supplier_name;
          return i;
        }) || [];
    } catch (e) {
      console.error(e);
    } finally {
      optionLoading.value = false;
    }
  } else {
    supplierOption.value = [];
  }
};

const data = reactive({
  supplierInfo: null,
});

const { supplierInfo } = toRefs(data);

const optionLoading = ref(false);
const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  ids.value[data.name] = data.ids;
  tableData.value = [];
  supplierList.value = [];
  getList(ids.value);
  visible.value = true;
};

const getList = async (val) => {
  try {
    const { data } = await getSupplier(val);
    const { data: skuSupplierList } = await getSKUSupplierList(val);
    tableData.value = data.map((i) => {
      i.is_refund_tax_init = i.is_refund_tax;
      i.tooltip = `<商品资料变更单>存在待审核数据，请审核通过再进行调整；
           当前审核节点：${i.change_detail?.node_name}；当前审核人：${i.change_detail?.user_name}`;
      return i;
    });
    supplierList.value = skuSupplierList;
  } catch (error) {}
};

const handleSupplierChange = (val, row) => {
  const findSupplier = supplierList.value.find(
    (i) => i.supplier_id == val && i.sku_id == row.sku_id
  );

  if (findSupplier) {
    row.is_refund_tax = findSupplier.is_refund_tax;
    row.supplier_name = findSupplier.supplier_name;
    row.supplier_code = findSupplier.supplier_code;
    row.supplier_id = findSupplier.supplier_id;
    row.invoice_tax_rate = findSupplier.invoice_tax_rate;
    row.tax_rate = findSupplier.tax_rate;
    row.unit_price = findSupplier.unit_price;
    row.unit_price_tax = findSupplier.unit_price_tax;
    row = blurcalculate(row, "tax_rate");
  } else {
    const supplierItem = supplierOption.value.find((i) => i.s_id == val);
    if (supplierItem.is_invoice == 1) {
      row.is_refund_tax = 2;
    } else {
      row.is_refund_tax = 3;
    }
    row.supplier_name = supplierItem.supplier_name;
    row.supplier_code = supplierItem.supplier_code;
    row.supplier_id = supplierItem.value;

    if (row.is_refund_tax == 2) {
      row.invoice_tax_rate =
        supplierItem.finance_tax && supplierItem.finance_tax != "0.00"
          ? supplierItem.finance_tax
          : 13;
      row.tax_rate =
        supplierItem.supplier_tax_rate && supplierItem.supplier_tax_rate != "0.00"
          ? supplierItem.supplier_tax_rate
          : 0;
    } else if (row.is_refund_tax == 3) {
      row.invoice_tax_rate = 0;
      row.tax_rate = 0;
    }
    row = blurcalculate(row, "tax_rate");
  }
};

const close = () => {
  tableData.value = [];
  visible.value = false;
};

const handleSelectSupplier = (type, index) => {
  if (type == "batch") {
    rowIndex.value = null;
  } else {
    rowIndex.value = index;
  }
  visibleSupplier.value = true;
};

const save = async () => {
  const messageArray = [];
  tableData.value.forEach((item, index) => {
    if (
      item.is_refund_tax == 2 &&
      (Number(item.tax_rate) > 13 || Number(item.tax_rate) == 0)
    ) {
      messageArray.push(`第${index + 1}项，供应商税点必须维护>0,<=13的值`);
    }
    if (item.is_refund_tax == 2 && Number(item.invoice_tax_rate) != 13) {
      messageArray.push(`第${index + 1}项，发票税点必须为13`);
    }

    if (Number(item.unit_price) > Number(item.unit_price_tax)) {
      messageArray.push(`第${index + 1}项，采购含税价必须>=采购未税报价,请修改`);
    }
  });
  if (messageArray && messageArray.length) {
    return ElMessageBox({
      title: "提示",
      message: <div>{messageArray.map((d) => h("p", null, d))}</div>,
    });
  }

  const sku_ids = tableData.value
    .map((i) => {
      if (i.goods_sku?.dev_status >= 4) {
        return i.goods_sku?.id;
      }
    })
    .filter((i) => i);

  const is_change = tableData.value.some(
    (i) =>
      i.goods_sku?.dev_status == 4 &&
      i.is_refund_tax == 2 &&
      change_order_category.includes(i.goods_spu.spu_category[0])
  );

  if (sku_ids && is_change) {
    const is_confirm = await handleConfirm(sku_ids);
    if (!is_confirm) return;
  }

  try {
    let data = tableData.value.map((i) => {
      return {
        id: i.id,
        supplier_id: i.supplier_id,
        supplier_name: i.supplier_name,
        supplier_code: i.supplier_code,
        unit_price: i.unit_price,
        unit_price_tax: i.unit_price_tax,
        purchase_untaxed_price: i.purchase_untaxed_price,
        tax_rate: i.tax_rate,
        invoice_tax_rate: i.invoice_tax_rate,
        is_refund_tax: i.is_refund_tax,
      };
    });
    if (!data.length) return ElMessage.warning("暂无供应商数据");
    const res = await batchUpdateSupplier({ goods_sku_supplier: data });
    ElMessage.success(res.message);
    close();
  } catch (e) {
    throw Error(e);
  }
};

const handleConfirm = (sku_ids) => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await getSKUSupplier({ sku_ids });
      if (res.data.length) {
        tableData.value.forEach((i) => {
          res.data.forEach((j) => {
            const findItem = j.goods_sku_supplier.find(
              (k) =>
                k.sku_id == i.goods_sku?.id &&
                k.supplier_id == i.supplier_id &&
                i.is_default_supplier
            );
            if (findItem) {
              i.is_change = 0;
            } else {
              i.is_change = 1;
            }
          });
        });

        const is_change = tableData.value.some((i) => {
          const is_oversea_location = oversea_location_category.includes(
            i.goods_spu.spu_category[0]
          );
          const is_change_order = change_order_category.includes(
            i.goods_spu.spu_category[0]
          );

          const is_flag =
            i.goods_sku?.dev_status >= 4 &&
            is_change_order &&
            !i.goods_sku?.is_combination &&
            ((i.is_refund_tax_init == 3 && i.is_refund_tax == 2) ||
              (i.is_change &&
                (i.is_refund_tax == 2 ||
                  (i.is_refund_tax == 3 && is_oversea_location))) ||
              (i.is_change == 0 &&
                is_oversea_location &&
                i.is_refund_tax_init != i.is_refund_tax));
          return is_flag;
        });

        if (is_change) {
          ElMessageBox.confirm(
            "SKU开发状态=通过，且绑定的供应商存在是否退税=退税；更换默认供应商，或者修改退税供应商的‘报关中文名’、‘报关单位’、‘规格型号’、‘海关编码’、‘退税率’、‘申报要素’，点击确认后，系统将自动生成变更单，审核通过后执行修改，是否确认修改？",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(async () => {
              resolve(true);
            })
            .catch(() => {
              reject(false);
            });
        } else {
          resolve(true);
        }
      } else {
        reject(false);
      }
    } catch (e) {
      reject(false);
      throw Error(e);
    }
  });
};

const visibleSupplier = ref(false);
const formValues = reactive({
  supplier_id: null,
  supplier_name: null,
  finance_tax: null,
  tax_rate: null,
});

const BatchSupplierChange = (val) => {
  const supplierItem = supplierOption.value.find((i) => i.s_id == formValues.supplier_id);
  supplierInfo.value = supplierItem;
};

const saveSupplier = async () => {
  if (rowIndex.value === null) {
    const is_wait_change_order = tableData.value.every((i) => i.is_wait_change_order);

    if (is_wait_change_order) {
      ElMessage.error("当前勾选全部数据都存在待审核的数据，请审核通过后再进行调整。");
      closeSupplier();
      return;
    }

    tableData.value.forEach((i) => {
      if (i.is_wait_change_order == 1) {
        return;
      }
      const findSupplier = supplierList.value.find(
        (j) => j.supplier_name == formValues.supplier_name && j.sku_id == i.sku_id
      );

      if (findSupplier) {
        i.is_refund_tax = findSupplier.is_refund_tax;
        i.supplier_name = findSupplier.supplier_name;
        i.supplier_id = findSupplier.value;
        i.supplier_code = findSupplier.supplier_code;
        i.invoice_tax_rate = findSupplier.invoice_tax_rate;
        i.tax_rate = findSupplier.tax_rate;
        i.unit_price = findSupplier.unit_price;
        i.unit_price_tax = findSupplier.unit_price_tax;
        i = blurcalculate(i, "tax_rate");
      } else {
        const supplierItem = supplierInfo.value;
        i.supplier_id = supplierItem.value;
        i.supplier_name = supplierItem.supplier_name;
        i.supplier_code = supplierItem.supplier_code;
        i.invoice_tax_rate =
          supplierItem.finance_tax && supplierItem.finance_tax != "0.00"
            ? supplierItem.finance_tax
            : 13;
        i.tax_rate =
          supplierItem.supplier_tax_rate && supplierItem.supplier_tax_rate != "0.00"
            ? supplierItem.supplier_tax_rate
            : 0;

        if (supplierItem.is_invoice == 1) {
          i.is_refund_tax = 2;
        } else {
          i.is_refund_tax = 3;
          i.invoice_tax_rate = 0;
          i.tax_rate = 0;
        }
        nextTick(() => {
          i = blurcalculate(i, "tax_rate");
        });
      }
    });
  } else {
    const row = tableData.value[rowIndex.value];
    handleSupplierChange(formValues.supplier_id, row);
  }
  closeSupplier();
};

const closeSupplier = () => {
  visibleSupplier.value = false;
  formValues.supplier_id = null;
  formValues.supplier_name = null;
  formValues.supplier_code = null;
};

defineExpose({ open });

const blurcalculate = (row, field) => {
  const { unit_price_tax, tax_rate, unit_price } = row;
  if (field == "unit_price") {
    row.unit_price_tax = (Number(unit_price) * (1 + tax_rate / 100)).toFixed(2);
  } else if (field == "unit_price_tax") {
    row.unit_price = (Number(row.unit_price_tax) / (1 + row.tax_rate / 100)).toFixed(2);
  } else if (field == "tax_rate" && unit_price) {
    row.unit_price_tax = (Number(row.unit_price) * (1 + row.tax_rate / 100)).toFixed(2);
  } else if (field == "tax_rate" && unit_price_tax) {
    row.unit_price = (Number(row.unit_price_tax) / (1 + row.tax_rate / 100)).toFixed(2);
  } else if (field == "unit_price" && unit_price_tax) {
    row.tax_rate = (
      ((Number(row.unit_price_tax) - Number(row.unit_price)) / Number(row.unit_price)) *
      100
    ).toFixed(2);
  } else if (field == "unit_price_tax" && unit_price) {
    row.tax_rate = (
      ((Number(row.unit_price_tax) - Number(row.unit_price)) / Number(row.unit_price)) *
      100
    ).toFixed(2);
  }
  nextTick(() => {
    if (
      row.unit_price &&
      row.unit_price_tax &&
      Number(row.unit_price) > Number(row.unit_price_tax)
    ) {
      ElMessage.error("采购含税价必须>=采购未税报价,请修改");
    }
    row.purchase_untaxed_price = (
      row.unit_price_tax /
      (1 + row.invoice_tax_rate / 100)
    ).toFixed(2);
    return row;
  });
};

const changeRefundTax = (row) => {
  if (row.is_refund_tax == 3) {
    row.tax_rate = 0;
    row.invoice_tax_rate = 0;
    blurcalculate(row, "tax_rate");
  } else {
    if (!row.supplier_code) return;
    const data = {
      pageNum: 1,
      pageSize: 999,
      supplier_code: row.supplier_code,
      supplier_name: row.supplier_name,
    };

    getSupplierList(data)
      .then((res) => {
        row.tax_rate = res.data[0].supplier_tax_rate;
        row.invoice_tax_rate = res.data[0].finance_tax;
        blurcalculate(row, "tax_rate");
      })
      .finally(() => {});
  }
};
</script>

<style lang="scss" scoped>
.footer-btn {
  :deep(.el-button + .el-button) {
    margin-left: 8px !important;
  }
}

:deep(.vxe-pulldown--panel) {
  z-index: 99999 !important;
}
.updateSupplier {
  .el-button--primary {
    :deep(span) {
      color: var(--el-color-primary) !important;
    }
  }
}
</style>
